<template>
    <div v-loading="loading" element-loading-text="文件上传中......">
        <!--查询表单-->
        <div class="search-div" style="margin-bottom: 10px;">
            <el-form label-width="70px" size="small">
                <el-row>
                    <!-- <el-col :span="8">
                        <el-form-item label="关键字">
                            <el-input style="width: 95%" v-model="searchObj.name" placeholder="宿舍名"></el-input>
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="8">
                        <el-form-item label="流程类型">
                            <el-input style="width: 95%" v-model="searchObj.bpmnType"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="部署时间">
                            <el-date-picker v-model="createTimes" type="datetimerange" range-separator="至"
                                start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss"
                                style="margin-right: 10px;width: 100%;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row style="display:flex">
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData()">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetData">重置</el-button>
                </el-row>
            </el-form>
        </div>

        <!-- 工具条 -->
        <div class="tools-div">
            <el-button type="success" icon="el-icon-plus" size="mini" @click="deploy()">流程定义部署</el-button>
        </div>

        <el-dialog title="部署流程定义文件" :visible.sync="dialogVisible" width="40%">
            <el-form ref="dataForm" :rules="rules" :model="form" label-width="150px" size="small"
                style="padding-right: 40px">
                <el-form-item label="流程类型" prop="bpmnType">
                    <el-input v-model="form.bpmnType"></el-input>
                </el-form-item>
                <el-form-item label="流程定义文件" prop="bpmnFile">
                    <el-upload class="upload-demo" ref="upload" :action="uploadUrl" :limit="1"
                        :before-upload="handleBeforeUpload" :on-change="handleChange" :file-list="fileList"
                        :auto-upload="false">
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传bpmn/zip/xml文件，且不超过5M</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="描述信息" prop="info">
                    <el-input type="textarea" v-model="form.info"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel()" size="small" icon="el-icon-refresh-right">取 消</el-button>
                <el-button type="primary" icon="el-icon-check" @click="submit()" size="small">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 表格 -->
        <el-table v-loading="listLoading" :data="list" stripe border style="width: 100%; margin-top: 10px">
            <el-table-column label="序号" width="70" align="center">
                <template slot-scope="scope">
                    {{ (page - 1) * limit + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column prop="bpmnLabel" label="流程名称" />
            <el-table-column prop="bpmnType" label="流程类型" />
            <el-table-column prop="processDefinitionKey" label="流程定义key" width="160" />
            <el-table-column prop="createTime" label="创建时间" />

            <el-table-column prop="version" label="版本号" width="160" />
            <el-table-column prop="info" label="描述信息" width="160" />
            
            <el-table-column prop="bpmnFile" label="流程文件" width="100">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handlePreview(scope.row)" title="预览">预览</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="bpmnFile" label="流程图" width="100">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleImage(scope.row)" title="预览">查看</el-button>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="200" align="center">
                <template slot-scope="scope">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.id)"
                        title="撤销" />
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination :current-page="page" :total="total" :page-size="limit" style="padding: 30px 0; text-align: center"
            layout="total, prev, pager, next, jumper" @current-change="fetchPageList" />

        <el-dialog :title="preview.title" :visible.sync="preview.open" width="80%" top="Svh" append-to-body
            class="scrollbar">
            <pre><code class="hljs" v-html="highlightedCode()"></code></pre>
        </el-dialog>
        <el-dialog :title="bpmnImage.title" :visible.sync="bpmnImage.open" width="80%" top="Svh" append-to-body
            class="scrollbar">
            <img :src="bpmnImage.data">
        </el-dialog>
    </div>
</template>
  
<script>
// 导入
import api from "@/api/definition/definition.js";


import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
import xml from "@/languages/xml";
hljs.registerLanguage("xml",require("highlight.js/lib/languages/xml"))
hljs.registerLanguage("xml", xml);



const defaultForm = {
    id: '',
    bpmnType: '',
    bpmnLabel: '',
    processDefinitionKey: '',
    version: '',
    info: '',
}
export default {
    data() {
        return {
            list: [],
            page: 1,
            limit: 5,
            total: 0,
            searchObj: {},
            listLoading: false,
            dialogVisible: false,
            definition: defaultForm,
            createTimes: [],

            //流程图
            bpmnImage:{
                title:'流程图',
                open:false,
                data:null
            },
            //流程文件  
            preview: {
                title: '流程文件',
                open: false,
                code: ''
            },

            //表单参数
            form: {
                bpmnType: null,
                bpmnFile: null,
                info: null
            },
            //表单效验
            rules: {
                bpmnType: [
                    { required: true, message: '请选择审核类型', trigger: 'change' }
                ],
                info: [
                    { required: true, message: '请输入备注信息', trigger: 'blur' }
                ]
            },
            uploadUrl: "",
            fileList: [],
            loading: false,
            VideodialogVisible: false
        };
    },

    created() {
        //this.listLoading=true;
        this.fetchPageList();
        this.findAll();
    },
    methods: {
        highlightedCode() {
            const result = hljs.highlight('xml', this.preview.code || "", true);
            return result.value || '&nbsp;';
        },

        handleChange(file, fileList) {
            this.fileList = fileList;
        },
        //文件开始上传,开始屏幕遮罩
        handleBeforeUpload(file) {
            // this.loading = true;
            const fileName = file.name.split('.');
            const fileExt = fileName[fileName.length - 1];
            if (['bpmn', 'zip', 'xml'].indexOf(fileExt) < 0) {
                this.$message.error("文件格式不正确");
                return false;
            }
            return true;
        },

        submit() {
            // 触发表单验证
            this.$refs.dataForm.validate((valid) => {
                if (valid) {
                    // 表单验证通过，执行保存或更新逻辑
                    if (this.fileList.length === 0) {
                        this.$message.error('请选择要部署的文件');
                        return false;
                    }
                    if (!this.handleBeforeUpload(this.fileList[0])) {//文件上传之前的判断
                        return false;
                    }
                    // this.form.bpmnFile = this.fileList[0];

                    console.log(this.fileList[0].raw);

                    api.deployBpmn({
                        ...this.form,
                        bpmnFile: this.fileList[0].raw //二进制文件数据
                    }).then(() => {
                        this.$message({
                            type: "success",
                            message: "流程定义部署成功!",
                        });
                        this.fetchPageList();
                    })
                    this.cancel();
                } else {
                    // 表单验证未通过，提示用户
                    return false;
                }
            });
        },
        deploy() {
            this.dialogVisible = true;
            this.form = {}

        },

        handlePreview(row){
            // 
            console.log("进入获取流程文件的方法")
            const type = "xml";
            api.getById(row.id,type).then(resp=>{
                console.log("流程文件：",resp)
                this.preview.data = resp;
            })

            this.preview.open = true;
        },
        handleImage(row){
            // 
            console.log("进入获取流程图的方法")
            const type = "image";
            api.getById(row.id,type).then(resp=>{
                console.log("流程图：",resp)
                this.bpmnImage.data = resp.data;
            })

            this.bpmnImage.open = true;
        },
        removeDataById(id) {
            this.$confirm("是否撤销?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                api.removeById(id).then((response) => {
                    this.$message({
                        type: "success",
                        message: "删除成功!",
                    });
                    this.fetchPageList();
                });
            });
        },
        // 取消按钮
        cancel() {
            this.dialogVisible = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                bpmnType: null,
                info: null
            };
            this.fileList = [];
            this.resetForm("form");
        },

        resetData() {
            //1.清空搜索条件
            this.searchObj = {};
            //2.再次刷新列表
            this.fetchPageList();
        },
        fetchPageList(page = 1) {
            this.page = page;
            if (this.createTimes && this.createTimes.length == 2) {
                this.searchObj.createTimeBegin = this.createTimes[0];
                this.searchObj.createTimeEnd = this.createTimes[1];
            }
            api
                .getPageInfo(this.page, this.limit, this.searchObj)
                .then((response) => {
                    // this.listLoading=false;
                    // console.log(response);
                    this.list = response.data.records;
                    this.total = response.data.total;
                });
        },
    },
};
</script>
  
<style lang="less" scoped></style>